"""
面试管理模型
"""
from django.db import models
from django.conf import settings
from students.models import Student


class InterviewCategory(models.Model):
    """面试分类"""
    
    name = models.CharField(max_length=100, unique=True, verbose_name='分类名称')
    description = models.TextField(blank=True, null=True, verbose_name='分类描述')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'interviews_category'
        verbose_name = '面试分类'
        verbose_name_plural = '面试分类'
        ordering = ['name']
        
    def __str__(self):
        return self.name


class InterviewQuestion(models.Model):
    """面试题库"""
    
    DIFFICULTY_CHOICES = [
        ('easy', '简单'),
        ('medium', '中等'),
        ('hard', '困难'),
    ]
    
    category = models.ForeignKey(InterviewCategory, on_delete=models.CASCADE, verbose_name='所属分类')
    question = models.TextField(verbose_name='题目内容')
    answer = models.TextField(blank=True, null=True, verbose_name='参考答案')
    difficulty = models.CharField(max_length=10, choices=DIFFICULTY_CHOICES, default='medium', verbose_name='难度')
    tags = models.CharField(max_length=200, blank=True, null=True, verbose_name='标签')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='创建人')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'interviews_question'
        verbose_name = '面试题目'
        verbose_name_plural = '面试题目'
        ordering = ['-created_at']
        
    def __str__(self):
        return f"{self.category.name} - {self.question[:50]}"


class InterviewApplication(models.Model):
    """面试申请"""

    TYPE_CHOICES = [
        ('practice', '练习面试'),
        ('mock', '模拟面试'),
        ('assessment', '评估面试'),
        ('career_guidance', '职业指导'),
    ]

    STATUS_CHOICES = [
        ('pending', '待审核'),
        ('approved', '已通过'),
        ('rejected', '已拒绝'),
        ('scheduled', '已安排'),
        ('completed', '已完成'),
        ('expired', '已过期'),
        ('cancelled', '已取消'),
    ]

    student = models.ForeignKey(Student, on_delete=models.CASCADE, verbose_name='申请学生')
    teacher = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        limit_choices_to={'role__in': ['admin', 'teacher']},
        verbose_name='指导老师'
    )
    interview_type = models.CharField(max_length=20, choices=TYPE_CHOICES, verbose_name='面试类型')
    title = models.CharField(max_length=200, verbose_name='申请标题')
    description = models.TextField(verbose_name='申请说明')

    # 申请时间偏好
    preferred_date = models.DateField(verbose_name='期望日期')
    preferred_time_start = models.TimeField(verbose_name='期望开始时间')
    preferred_time_end = models.TimeField(verbose_name='期望结束时间')

    # 审核信息
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='申请状态')
    reviewed_at = models.DateTimeField(blank=True, null=True, verbose_name='审核时间')
    review_comments = models.TextField(blank=True, null=True, verbose_name='审核意见')

    # 安排的面试时间（审核通过后设置）
    scheduled_date = models.DateField(blank=True, null=True, verbose_name='安排日期')
    scheduled_time_start = models.TimeField(blank=True, null=True, verbose_name='安排开始时间')
    scheduled_time_end = models.TimeField(blank=True, null=True, verbose_name='安排结束时间')
    location = models.CharField(max_length=200, blank=True, null=True, verbose_name='面试地点')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='申请时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'interviews_application'
        verbose_name = '面试申请'
        verbose_name_plural = '面试申请'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.student.name} - {self.title}"

    @property
    def is_expired(self):
        """检查是否已过期"""
        if self.status == 'scheduled' and self.scheduled_date:
            from django.utils import timezone
            scheduled_datetime = timezone.datetime.combine(
                self.scheduled_date,
                self.scheduled_time_end or self.scheduled_time_start
            )
            return timezone.now() > timezone.make_aware(scheduled_datetime)
        return False


class Interview(models.Model):
    """面试记录"""

    TYPE_CHOICES = [
        ('practice', '练习面试'),
        ('mock', '模拟面试'),
        ('assessment', '评估面试'),
        ('career_guidance', '职业指导'),
    ]

    STATUS_CHOICES = [
        ('scheduled', '已安排'),
        ('in_progress', '进行中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
        ('expired', '已过期'),
    ]
    
    application = models.OneToOneField(
        InterviewApplication,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        verbose_name='关联申请'
    )
    student = models.ForeignKey(Student, on_delete=models.CASCADE, verbose_name='学生')
    interviewer = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        limit_choices_to={'role__in': ['admin', 'teacher']},
        verbose_name='面试官'
    )
    interview_type = models.CharField(max_length=20, choices=TYPE_CHOICES, verbose_name='面试类型')
    title = models.CharField(max_length=200, verbose_name='面试标题')
    description = models.TextField(blank=True, null=True, verbose_name='面试描述')
    
    scheduled_time = models.DateTimeField(verbose_name='预定开始时间')
    scheduled_end_time = models.DateTimeField(blank=True, null=True, verbose_name='预定结束时间')
    actual_start_time = models.DateTimeField(blank=True, null=True, verbose_name='实际开始时间')
    actual_end_time = models.DateTimeField(blank=True, null=True, verbose_name='实际结束时间')
    
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='scheduled', verbose_name='状态')
    location = models.CharField(max_length=200, blank=True, null=True, verbose_name='面试地点')
    
    # 评分
    overall_score = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, verbose_name='总体评分')
    feedback = models.TextField(blank=True, null=True, verbose_name='面试反馈')
    suggestions = models.TextField(blank=True, null=True, verbose_name='改进建议')
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'interviews_interview'
        verbose_name = '面试记录'
        verbose_name_plural = '面试记录'
        ordering = ['-scheduled_time']
        
    def __str__(self):
        return f"{self.student.name} - {self.title}"
    
    @property
    def duration(self):
        """面试时长"""
        if self.actual_start_time and self.actual_end_time:
            return self.actual_end_time - self.actual_start_time
        return None


class InterviewQuestionAssignment(models.Model):
    """面试题目分配"""
    
    interview = models.ForeignKey(Interview, on_delete=models.CASCADE, verbose_name='面试')
    question = models.ForeignKey(InterviewQuestion, on_delete=models.CASCADE, verbose_name='题目')
    order = models.IntegerField(default=0, verbose_name='顺序')
    student_answer = models.TextField(blank=True, null=True, verbose_name='学生回答')
    score = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, verbose_name='得分')
    comments = models.TextField(blank=True, null=True, verbose_name='评语')
    
    class Meta:
        db_table = 'interviews_question_assignment'
        verbose_name = '面试题目分配'
        verbose_name_plural = '面试题目分配'
        unique_together = ['interview', 'question']
        ordering = ['interview', 'order']
        
    def __str__(self):
        return f"{self.interview.title} - {self.question.question[:30]}"


class InterviewResult(models.Model):
    """面试结果记录"""

    interview = models.OneToOneField(Interview, on_delete=models.CASCADE, verbose_name='面试')

    # 老师填写的评价
    teacher_feedback = models.TextField(blank=True, null=True, verbose_name='老师反馈')
    teacher_score = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, verbose_name='老师评分')
    teacher_suggestions = models.TextField(blank=True, null=True, verbose_name='老师建议')
    teacher_submitted_at = models.DateTimeField(blank=True, null=True, verbose_name='老师提交时间')

    # 学生填写的反馈
    student_feedback = models.TextField(blank=True, null=True, verbose_name='学生反馈')
    student_self_score = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, verbose_name='学生自评分')
    student_experience = models.TextField(blank=True, null=True, verbose_name='面试体验')
    student_submitted_at = models.DateTimeField(blank=True, null=True, verbose_name='学生提交时间')

    # 面试是否完成（双方都提交后才算完成）
    is_completed = models.BooleanField(default=False, verbose_name='是否完成')
    completed_at = models.DateTimeField(blank=True, null=True, verbose_name='完成时间')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'interviews_result'
        verbose_name = '面试结果'
        verbose_name_plural = '面试结果'

    def __str__(self):
        return f"{self.interview.student.name} - 面试结果"

    def check_completion(self):
        """检查是否双方都已提交"""
        if self.teacher_submitted_at and self.student_submitted_at and not self.is_completed:
            from django.utils import timezone
            self.is_completed = True
            self.completed_at = timezone.now()
            self.save()


class InterviewEvaluation(models.Model):
    """面试评价（详细评分）"""

    interview = models.OneToOneField(Interview, on_delete=models.CASCADE, verbose_name='面试')

    # 各项评分
    communication_score = models.DecimalField(max_digits=4, decimal_places=2, verbose_name='沟通表达')
    technical_score = models.DecimalField(max_digits=4, decimal_places=2, verbose_name='专业技能')
    problem_solving_score = models.DecimalField(max_digits=4, decimal_places=2, verbose_name='问题解决')
    attitude_score = models.DecimalField(max_digits=4, decimal_places=2, verbose_name='工作态度')
    overall_impression = models.DecimalField(max_digits=4, decimal_places=2, verbose_name='整体印象')

    # 详细评价
    strengths = models.TextField(blank=True, null=True, verbose_name='优势')
    weaknesses = models.TextField(blank=True, null=True, verbose_name='不足')
    improvement_suggestions = models.TextField(blank=True, null=True, verbose_name='改进建议')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'interviews_evaluation'
        verbose_name = '面试评价'
        verbose_name_plural = '面试评价'

    def __str__(self):
        return f"{self.interview.student.name} - 面试评价"

    @property
    def average_score(self):
        """平均分"""
        scores = [
            self.communication_score,
            self.technical_score,
            self.problem_solving_score,
            self.attitude_score,
            self.overall_impression
        ]
        return sum(scores) / len(scores)


class InterviewTask(models.Model):
    """面试任务"""
    
    STATUS_CHOICES = [
        ('pending', '待完成'),
        ('completed', '已完成'),
        ('overdue', '已逾期'),
    ]
    
    student = models.ForeignKey(Student, on_delete=models.CASCADE, verbose_name='学生')
    assigned_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        limit_choices_to={'role__in': ['admin', 'teacher']},
        verbose_name='分配人'
    )
    title = models.CharField(max_length=200, verbose_name='任务标题')
    description = models.TextField(verbose_name='任务描述')
    questions = models.ManyToManyField(InterviewQuestion, verbose_name='练习题目')
    
    due_date = models.DateTimeField(verbose_name='截止时间')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='状态')
    completion_date = models.DateTimeField(blank=True, null=True, verbose_name='完成时间')
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'interviews_task'
        verbose_name = '面试任务'
        verbose_name_plural = '面试任务'
        ordering = ['-created_at']
        
    def __str__(self):
        return f"{self.student.name} - {self.title}"


class PracticeSession(models.Model):
    """面试练习会话"""

    STATUS_CHOICES = [
        ('active', '进行中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]

    student = models.ForeignKey(Student, on_delete=models.CASCADE, verbose_name='学生')
    job_id = models.CharField(max_length=50, blank=True, null=True, verbose_name='岗位ID')
    job_title = models.CharField(max_length=200, blank=True, null=True, verbose_name='岗位名称')
    company_name = models.CharField(max_length=200, blank=True, null=True, verbose_name='公司名称')

    # Dify相关字段
    conversation_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='Dify会话ID')

    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    started_at = models.DateTimeField(auto_now_add=True, verbose_name='开始时间')
    ended_at = models.DateTimeField(blank=True, null=True, verbose_name='结束时间')

    # 会话统计
    message_count = models.IntegerField(default=0, verbose_name='消息数量')
    duration_minutes = models.IntegerField(blank=True, null=True, verbose_name='持续时间(分钟)')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'interviews_practice_session'
        verbose_name = '面试练习会话'
        verbose_name_plural = '面试练习会话'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.student.name} - {self.job_title or '未知岗位'} - {self.started_at.strftime('%Y-%m-%d %H:%M')}"


class PracticeMessage(models.Model):
    """面试练习消息"""

    ROLE_CHOICES = [
        ('user', '用户'),
        ('assistant', '助手'),
    ]

    session = models.ForeignKey(PracticeSession, on_delete=models.CASCADE, related_name='messages', verbose_name='会话')
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, verbose_name='角色')
    content = models.TextField(verbose_name='消息内容')

    # Dify相关字段
    message_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='Dify消息ID')
    task_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='Dify任务ID')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'interviews_practice_message'
        verbose_name = '面试练习消息'
        verbose_name_plural = '面试练习消息'
        ordering = ['created_at']

    def __str__(self):
        return f"{self.session} - {self.role} - {self.created_at.strftime('%H:%M:%S')}"


class PracticeRecord(models.Model):
    """面试练习记录"""

    session = models.OneToOneField(PracticeSession, on_delete=models.CASCADE, related_name='record', verbose_name='会话')

    # 练习总结
    summary = models.TextField(blank=True, null=True, verbose_name='练习总结')
    strengths = models.TextField(blank=True, null=True, verbose_name='优势分析')
    weaknesses = models.TextField(blank=True, null=True, verbose_name='不足分析')
    suggestions = models.TextField(blank=True, null=True, verbose_name='改进建议')

    # 评分（1-10分）
    overall_score = models.FloatField(blank=True, null=True, verbose_name='总体评分')
    communication_score = models.FloatField(blank=True, null=True, verbose_name='沟通表达评分')
    technical_score = models.FloatField(blank=True, null=True, verbose_name='专业技能评分')
    attitude_score = models.FloatField(blank=True, null=True, verbose_name='态度表现评分')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'interviews_practice_record'
        verbose_name = '面试练习记录'
        verbose_name_plural = '面试练习记录'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.session.student.name} - {self.session.job_title or '未知岗位'} - 记录"
